////////////////////////////////////////////////////////////////////////////////
// 
//flex 与后台c#数据进行实时交互
////////////////////////////////////////////////////////////////////////////////
package com.esri.viewer
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import mx.modules.Module;
	
	public class ownerSocket extends Module
	{
		
		/** 
		 * Socket 套接字 
		 */  
		private var socket:Socket;
		/** 
		 * 域名或者主机Ip 
		 */  
		private var host:String;  
		/** 
		 * 通讯端口 
		 */  
		private var port:int;  
		/** 
		 * 接收数据的类型 
		 */  
		public var RecieveDataType:String="CHARS";  
		/** 
		 * 发送数据的类型 
		 */  
		public var SendDataType:String="";  
		
		/** 
		 * 通讯状态 
		 */  
		private var stateMap:Object;  
		/** 
		 * 字符类型 
		 */  
		public static const CHARS:String="CHARS";  
		/** 
		 * 字节类型 
		 */  
		public static const BYTES:String="BYTES";  
          
	   public function set ipAddress(value:String):void
	   {
		   this.host=value;
	   }
	   public function set hostPort(value:int):void
	   {
		   this.port=value;
	   }
	   
		public function ownerSocket()
		{
			socket=new Socket();
			socket.addEventListener(Event.CONNECT,onConnect);  
			socket.addEventListener(Event.CLOSE,onClose);  
			socket.addEventListener(IOErrorEvent.IO_ERROR,onIoError);  
			socket.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData); 
		}

		
		public function close():void{  
			socket.close();  
		}  

		private function onConnect(e:Event):void{  
			trace("正在连接服务器...");  
		}  
		private function onClose(e:Event):void{  
			trace("正在与服务器断开连接...");  
		}  
		private function onIoError(e:Event):void{  
			trace("正在与服务器断开连接...");  
		} 
		/** 
		 * 写入数据 
		 */  
		public function WriteDate(value:String):void{  
			  if(socket.connected)
				  socket.close();
			  
				socket.connect(host,port);  
				socket.writeMultiByte("hello server"+"\n","");		
		}  	
		/** 
		 * 处理Socket接收数据 
		 */  
		private function onSocketData(e:ProgressEvent):void{  
			if(RecieveDataType==BYTES){  
				var bytes:ByteArray;  
				socket.readBytes(bytes);  
				/*trace("收到的数据："+socket.bytesAvailable+"b/s"); 
				while(socket.bytesAvailable){ 
				var data:int=socket.readByte(); 
				trace(data); 
				}*/  
			}else if(RecieveDataType==CHARS){  
				var recieveData:String=socket.readUTFBytes(socket.bytesAvailable);  
				var resultObject:Object={
					value:recieveData
				};
				//广播接收到的数据
				ViewerContainer.dispatchEvent(new AppEvent(AppEvent.SOCKET_GETDATA,resultObject));
			}  
		}  
	}
}